package terminalresource

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"fmt"
)

// 获取终端资源列表
func (manage *TerminalResourceManage) GetTerminalResourceList(query *request.GetTerminalResourceListQuery) (response.PageData, error) {
	pageData := response.PageData{}

	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.TerminalResource{})
	if query.AreaName != "" {
		tx = tx.Where("area_name LIKE ?", "%"+query.AreaName+"%")
	}
	if query.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+query.Name+"%")
	}

	// 获取总记录数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return pageData, err
	}
	if total == 0 {
		pageData.List = []interface{}{}
		return pageData, nil
	}

	// 分页查询
	currentPage := query.CurrentPage
	numPerPage := query.NumPerPage
	if currentPage <= 0 {
		currentPage = 1
	}
	if numPerPage <= 0 {
		numPerPage = 50
	}
	offset := (currentPage - 1) * numPerPage
	tx = tx.Order("area_name ASC, name ASC").Limit(numPerPage).Offset(offset)

	var resourceList []response.GetTerminalResourceListResponseInfo
	if err := tx.Find(&resourceList).Error; err != nil {
		return pageData, err
	}

	pageData.CurrentPage = currentPage
	pageData.NumPerPage = numPerPage
	pageData.TotalCount = int(total)
	pageData.TotalPages = (pageData.TotalCount + numPerPage - 1) / numPerPage
	pageData.List = resourceList

	return pageData, nil
}

// 添加或修改终端资源
func (manage *TerminalResourceManage) AddOrUpdateTerminalResource(terminalResource *request.AddOrUpdateTerminalResourceQuery) error {
	db := manage.DataBase.DB()

	isUpdate := terminalResource.Id != ""

	if !isUpdate {
		resourceToCreate := dbModel.TerminalResource{
			Id:         commUtils.GenUUID(),
			AreaName:   terminalResource.AreaName,
			Name:       terminalResource.Name,
			PreviewUrl: terminalResource.PreviewUrl,
		}
		// 安全处理指针
		if terminalResource.SignalStatus != nil {
			resourceToCreate.SignalStatus = *terminalResource.SignalStatus
		}
		if err := db.Create(&resourceToCreate).Error; err != nil {
			return err
		}
	} else {
		idToUpdate := terminalResource.Id
		updateData := map[string]interface{}{
			"area_name":   terminalResource.AreaName,
			"name":        terminalResource.Name,
			"preview_url": terminalResource.PreviewUrl,
		}
		// 安全处理指针
		if terminalResource.SignalStatus != nil {
			updateData["signal_status"] = *terminalResource.SignalStatus
		}

		result := db.Model(&dbModel.TerminalResource{}).Where("id = ?", idToUpdate).Updates(updateData)
		if result.Error != nil {
			return result.Error
		}
		// 检查是否有记录被更新
		if result.RowsAffected == 0 {
			return fmt.Errorf("更新终端资源失败：ID 为 %d 的记录未找到", idToUpdate)
		}
	}

	return nil
}

// 删除终端资源
func (manage *TerminalResourceManage) DeleteTerminalResource(terminalResourceIds []string) error {
	if len(terminalResourceIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	result := db.Where("id IN ?", terminalResourceIds).Delete(&dbModel.TerminalResource{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("没有找到要删除的记录，ID列表可能无效或记录已被删除")
	}
	return nil
}

// 获取终端资源详情
func (manage *TerminalResourceManage) GetTerminalResourceDetail(query *request.GetTerminalResourceDetailQuery) (*response.GetTerminalResourceDetailResponse, error) {
	db := manage.DataBase.DB()
	
	var terminalResource dbModel.TerminalResource
	if err := db.Where("id = ?", query.TerminalResourceId).First(&terminalResource).Error; err != nil {
		return nil, fmt.Errorf("获取终端资源详情失败：%v", err)
	}
	
	response := &response.GetTerminalResourceDetailResponse{
		Id:           terminalResource.Id,
		AreaName:     terminalResource.AreaName,
		Name:         terminalResource.Name,
		SignalStatus: &terminalResource.SignalStatus,
		PreviewUrl:   terminalResource.PreviewUrl,
	}
	
	return response, nil
}